import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;

public class ProcessPaperSale extends HttpServlet
{
	public void doGet(HttpServletRequest request,HttpServletResponse response)throws ServletException,IOException
	{
		doPost(request,response);
	}//doPost

	public void doPost(HttpServletRequest request,HttpServletResponse response)throws ServletException,IOException
    {
		RequestDispatcher dispatcher = null;
		String event = request.getParameter("eventAction");
		if( event.equals("exit") )
		{
			dispatcher = request.getRequestDispatcher("/jsp/SimActivities.jsp");
			dispatcher.forward(request,response);
		}
		try
		{
			int cardid = Integer.parseInt(request.getParameter("cardid"));
			int outid = Integer.parseInt(request.getParameter("outid"));
			int count = Integer.parseInt(request.getParameter("count"));

			Class.forName("com.mysql.jdbc.Driver").newInstance();
			Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/airtel","root","root");
			Statement stmt = con.createStatement();
			Timestamp ts = null;
			int stock = 0;
			String flag = "";
			ResultSet rs = stmt.executeQuery("select count from paperstock where cardType='"+cardid+"'");
			if(rs.next())
			{
				stock = Integer.parseInt(rs.getString(1));
				flag = "true";
			}
			if(stock >= count)
			{
				stock -= count;
				int id = 0;
				rs = stmt.executeQuery("select max(id) from papersale");
				if(rs.next())
				{
					if( rs.getString(1) != null )
					{
						id = Integer.parseInt(rs.getString(1));
					}
				}
				id++;

				ts = new Timestamp( (new java.util.Date()).getTime() );
				stmt.executeUpdate("update paperstock set timestamp='"+ts+"', count='"+stock+"' where cardType='"+cardid+"'");	
				stmt.executeUpdate("insert into papersale values('"+id+"','"+ts+"','"+count+"','"+outid+"','"+cardid+"','"+flag+"')");
				request.setAttribute("msg", new String("Paper Stock Updated"));				
			}
			else
			{
				request.setAttribute("msg", new String("Sorry Paper Stock not available Available Stock is:'"+stock+"'"));    
			}
			Collection outletVector = new Vector();
			Collection cardVector = new Vector();

			rs = stmt.executeQuery("select id,name from outletdetails");
			while(rs.next())
			{
				outletVector.add(rs.getString(1));
				outletVector.add(rs.getString(2));
			}   
			request.setAttribute("outletnames",outletVector);

			rs = stmt.executeQuery("select id,cardType from cardtype where cardType not in ('cd99','cd599')");
			while(rs.next())
			{
				cardVector.add(rs.getString(1));
				cardVector.add(rs.getString(2));
			}   
			request.setAttribute("cardtypes",cardVector);
				
			dispatcher = request.getRequestDispatcher("/jsp/PaperSales.jsp");
			dispatcher.forward(request,response);
		}//try
		catch(Exception e)
		{
            e.printStackTrace();
		}//catch
	}//doPost
}//class